package com.seal.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.springframework.stereotype.Repository;

import com.seal.comm.utils.Page;
import com.seal.dao.BaseDaoImpl;
import com.seal.dao.IMessageDao;
import com.seal.dto.MessageDto;
import com.seal.model.Message;

@Repository("messageDaoImpl")
public class MessageDaoImpl extends BaseDaoImpl implements IMessageDao {

	public void addMessage(Message ca) throws Exception {
		this.save(ca);
	}

	public void updateMessage(Message ca) throws Exception {
		this.update(ca);
	}
	
	public void deleteMessage(Message ca) throws Exception {
		this.delete(ca);
	}
	
	public Message getMessageById(Long id) throws Exception {
		return (Message) this.select(Message.class, id);
	}
	
	public List<Message> getAllMessage(MessageDto messageDto, Page page)throws Exception {
		StringBuffer hql=new StringBuffer("from Message t where 1=1");
		if (null != messageDto.getFromDate()
				&& !"".equals(messageDto.getFromDate())) {
			hql.append(" and t.msgDate >= :fromDate");
		}
		
		if (null != messageDto.getToDate()
				&& !"".equals(messageDto.getToDate())) {
			hql.append(" and t.msgDate <= :toDate");
		}
		
		if (null != messageDto.getReplyFlag()) {
			hql.append(" and t.replyFlag = :replyFlag");
		}
		

		Query query = this.getSession().createQuery(hql.toString());
		query.setProperties(messageDto);
		if (null != page) {
			query.setFirstResult(page.getFirstResult());
			query.setMaxResults(page.getPageSize());
			String countSql="select count(t) "+hql.toString();

			Query queryCount = this.getSession().createQuery(countSql);
			queryCount.setProperties(messageDto);
			page.setTotalNumber(Integer.parseInt(queryCount.uniqueResult().toString()));
		}
		
		return query.list();
	}
}
